package com.susu.zookeeper.curator.model;

import com.susu.zookeeper.curator.enums.LockTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessLock;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.framework.recipes.locks.InterProcessSemaphoreMutex;

import java.util.concurrent.TimeUnit;

/**
 * @author susu
 */
@Slf4j
public class ZookeeperLock {

    private InterProcessLock interProcessLock;

    public ZookeeperLock(CuratorFramework client, String basePath, LockTypeEnum lockTypeEnum) {
        switch (lockTypeEnum) {
            case RE_LOCK:
                this.interProcessLock = new InterProcessMutex(client, basePath);
                break;
            case UN_RE_LOCK:
                this.interProcessLock = new InterProcessSemaphoreMutex(client, basePath);
                break;
            default:
                break;
        }
    }

    /**
     * 加锁
     *
     * @return 成功/失败
     */
    public boolean acquire() {
        boolean success = false;
        try {
            interProcessLock.acquire();
            success = true;
        } catch (Exception e) {
            log.error("获取锁失败,e:", e);
        }
        return success;
    }

    /**
     * 加锁
     *
     * @param time 时间
     * @param unit 时间类型
     * @return 成功/失败
     */
    public boolean acquire(long time, TimeUnit unit) {
        try {
            return interProcessLock.acquire(time, unit);
        } catch (Exception e) {
            log.error("获取锁失败,e:", e);
        }
        return false;
    }

    /**
     * 解除锁
     */
    public void release() {
        try {
            interProcessLock.release();
        } catch (Exception e) {
            log.error("释放锁失败,e:", e);
        }
    }
}
